<template>
  <el-container>
    <el-container>
      <el-header>
        <div class="left-panel">
          <el-button v-auth="'setting:user:add'" type="primary" icon="el-icon-plus" @click="add"></el-button>
          <el-button v-auth="'setting:user:del:batch'" type="danger" plain icon="el-icon-delete"
                     :disabled="selection.length===0"
                     @click="batch_del"></el-button>
          <el-button type="primary" plain :disabled="selection.length===0">分配角色</el-button>
          <el-button v-auth="'setting:user:reset:password:batch'" type="primary" plain :disabled="selection.length===0">
            密码重置
          </el-button>
        </div>
        <div class="right-panel">
          <div class="right-panel-search">
            <el-input v-model="search.name" placeholder="登录账号 / 姓名" clearable></el-input>
            <el-button type="primary" icon="el-icon-search" @click="upsearch"></el-button>
          </div>
        </div>
      </el-header>
      <el-main class="nopadding">
        <SailorTable ref="tableRef" :apiObj="Apis.api_setting.user.list" @selection-change="selectionChange" stripe
                     remoteSort remoteFilter>
          <el-table-column type="selection" width="50"></el-table-column>
          <el-table-column label="唯一标识" prop="uuid" min-width="250" align="center"></el-table-column>
          <el-table-column label="加入时间" prop="createdAt" min-width="140" sortable='custom'></el-table-column>
          <el-table-column label="头像" min-width="50" align="center">
            <template #default="scope">
              <el-avatar :src="scope.row.userAvatar" size="small"></el-avatar>
            </template>
          </el-table-column>
          <el-table-column label="登录账号" prop="userAccount" min-width="150"></el-table-column>
          <el-table-column label="用户昵称" prop="userName" min-width="150" sortable='custom'></el-table-column>
          <el-table-column label="所属角色" prop="userRole" min-width="300" sortable='custom'>
            <template #default="scope">
              <el-select @change="userRoleChange(scope.row,$event)" v-model="scope.row.userRole" multiple collapse-tags
                         collapse-tags-tooltip>
                <el-option v-for="item in roleList" :key="item.uuid" :label="item.roleCode"
                           :value="item.roleCode">
                  <span style="float: left">{{ item.roleName }}</span>
                  <span style="float: right;color: var(--el-text-color-secondary);font-size: 13px; ">
                    {{ item.roleCode }}
                  </span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" align="center" min-width="260">
            <template #default="scope">
              <el-button-group>
                <el-button v-auth="'setting:user:info'" text type="primary" size="small"
                           @click="table_show(scope.row, scope.$index)">查看
                </el-button>
                <el-button v-auth="'setting:user:edit'" text type="primary" size="small"
                           @click="table_edit(scope.row, scope.$index)">编辑
                </el-button>
                <el-button v-auth="'setting:user:reset:password'" text type="primary" size="small">
                  重置密码
                </el-button>
                <el-popconfirm title="确定删除吗？" @confirm="table_del(scope.row, scope.$index)">
                  <template #reference>
                    <el-button v-auth="'setting:user:del'" text type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </el-button-group>
            </template>
          </el-table-column>
        </SailorTable>
      </el-main>
    </el-container>
  </el-container>

  <save-dialog v-if="dialog.save" ref="saveRef" @success="handleSuccess" @closed="dialog.save=false"></save-dialog>

</template>

<script setup name="user">
import saveDialog from './save'
import {nextTick, onMounted, reactive, ref} from "vue";

import Apis from '@/api'
import SailorTable from "@/components/SailorTable/index.vue";
import {ElMessage, ElMessageBox} from "element-plus";


let roleList = reactive([])
let dialog = reactive({
  save: false
})

let selection = reactive([])
let search = reactive({
  name: null
})

let tableRef = ref()
let saveRef = ref()

onMounted(() => {
  nextTick(() => {
    getRole()
  })
})


// 角色变更
const userRoleChange = async (row, newValue) => {
  let res = await Apis.api_setting.user.change_role.post({
    uuid: row.uuid,
    role: JSON.stringify(newValue)
  });
  if (res.code === 0) {
    ElMessage.success("操作成功")
  } else {
    ElMessage.error(res.message)
  }
}
// 获取所有角色
const getRole = async () => {
  let res = await Apis.api_setting.role.list_all.get();
  if (res.code === 0) {
    Object.assign(roleList, res.data)
  } else {
    ElMessage.error(res.message)
  }
}
//添加
const add = () => {
  dialog.save = true
  nextTick(() => {
    saveRef.value.open()
  })
}
//编辑
const table_edit = (row) => {
  dialog.save = true
  nextTick(() => {
    saveRef.value.setData(JSON.parse(JSON.stringify(row)), 'edit')
  })
}
//查看
const table_show = (row) => {
  dialog.save = true
  nextTick(() => {
    saveRef.value.setData(row, 'show')
  })
}
//删除
const table_del = async (row, index) => {
  let res = await Apis.api_setting.user.del.post({uuid: [row.uuid]});
  if (res.code === 0) {
    //这里选择刷新整个表格 OR 插入/编辑现有表格数据
    tableRef.value.tableData.splice(index, 1);
    ElMessage.success("删除成功")
  } else {
    ElMessage.error(res.message)
  }
}
//批量删除
const batch_del = async () => {
  ElMessageBox.confirm(`确定删除选中的 ${selection.length} 项吗？`, '提示', {
    type: 'warning'
  }).then(async () => {
    let res = await Apis.api_setting.user.del.post({
      uuid: JSON.stringify(selection.map(item => item.uuid))
    });
    if (res.code === 0) {
      selection.forEach(item => {
        tableRef.value.tableData.forEach((itemI, indexI) => {
          if (item.uuid === itemI.uuid) {
            tableRef.value.tableData.splice(indexI, 1)
          }
        })
      })
      ElMessage.success("操作成功")
    } else {
      ElMessage.error(res.message)
    }
  }).catch(() => {

  })
}
//表格选择后回调事件
const selectionChange = (select) => {
  selection = select;
}
//搜索
const upsearch = () => {
  tableRef.value.upData(search)
}
//本地更新数据
const handleSuccess = (data, mode) => {
  if (mode === 'add') {
    data.id = new Date().getTime()
    tableRef.value.tableData.unshift(data)
  } else if (mode === 'edit') {
    tableRef.value.tableData.filter(item => item.id === data.id).forEach(item => {
      Object.assign(item, data)
    })
  }
}

</script>

<style>
</style>
